<?php

namespace Application\Controller;

use Zend\View\Renderer\PhpRenderer;
use Zend\View\Resolver;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Model\RechercheTable;
use Application\Model\Recherche;
use Zend\Session\Container; // We need this when using sessions
use ZendViewRendererRendererInterface as ViewRenderer;
use Application\Model\Information;

class DetailsSejourController extends AbstractActionController
{
	protected $rechercheTable;
	protected $SejourTable;
	protected $AgenceTable;
	protected $SejourDateTable;
	protected $ActivitesSejourTable;
	protected $SejourImageTable;
	protected $SejourDaybydayTable;
	protected $SejourFicheTable;
	protected $InformationTable;
	protected $MailService;
	protected $DateService;
	protected $StringService;

	/* action appelée via l'url rewriting */
	/* détails d'un séjour */
	/* model : hotel.com ;) */
    public function ficheAction()
    {
    	$this->layout('layout/layoutfiche');
    	
    	$isSejourVerifieSucces = false;

		$id = $this->params()->fromRoute('id');
		// $activite = $this->params()->fromRoute('activite');
		// $destination = $this->params()->fromRoute('destination');
		// $nomfiche = $this->params()->fromRoute('nomfiche');

		$sejourAVerifier = $this->getSejourTable()->details_pour_verif_sejour_unique( $id );

    	if( count($sejourAVerifier) === 1 ) {
			$isSejourVerifieSucces = $this->getSejourTable()->verifierConcordanceUrlSejour( 	$id,/* 
																								$activite, 
																								$destination, 
																								$nomfiche,*/ 
																								$sejourAVerifier );
    	}

    	if( !$isSejourVerifieSucces ) {
    		return $this->redirect()->toUrl("/");
    	} else {

    		$filtresEnClair = array();


    		$user_session = new Container('filtresession');
    		$filtresCourantSession = $user_session->filtresCourant;

    		if( $filtresCourantSession != null ) {
				$filtresEnClair = $this->getRechercheTable()->concatener_filtres_en_clair_pour_fiche_detail ( $filtresCourantSession );
			}

			// sortir bloc du layout ds un helper
			$this->layout()->setVariable("filtresEnClair", $filtresEnClair);

			// on va récupérer toutes les détails du séjour
			$detailsSejour = $this->getSejourTable()->details_d_un_sejour_unique( $id );
			$datesSejour = $this->getSejourDateTable()->fetchAll( $id );
			$daysByDaysSejour = $this->getSejourDaybydayTable()->fetchAll( $id );
			$sejourFiches = $this->getSejourFicheTable()->fetchAll( $id );
			$agenceDuSejour = $this->getAgenceTable()->getAgence( $detailsSejour->agenceId );

			/* Initialisation de la balise meta Titre */
			$this->layout()->setVariable("titreDeLaPage", $detailsSejour->titre . " - 1001treks");

			/* Initialisation de la balise og:image (réseaux sociaux) */
			$image = $this->getStringService()->RetrounerNomImageType( $detailsSejour->imageUrl, "-main");
			$this->layout()->setVariable("imageReseauxSociaux", "/img/galerie/sejour__" . $detailsSejour->id . "__/". $image);

			/* Initialisation de la balise meta Description */
			$resume = $this->getStringService()->RetirerSautLIgneTabChariot ( $detailsSejour->resume );
			$this->layout()->setVariable("descriptionDeLaPage", $resume);

			/* Calcul de l'image de l'agence */
			$agenceImage = $this->getStringService()->RetrounerNomImageType( $detailsSejour->agenceImageURL, "-min");
		 	$detailsSejour->agenceImageURL = $agenceImage;

		 	/* Thématiques du séjour */
		 	$sejoursSimilaires = $this->getSejourTable()->listeSejoursSimilaires( $detailsSejour->id, $detailsSejour->thematiques );
			
	        return new ViewModel(array(
		        'sjr' => $detailsSejour,
		        'sjr_dates' => $datesSejour,
		        'sjr_agence' => $agenceDuSejour,
		        'sjr_jours' => $daysByDaysSejour,
		        'sjr_fiche' => $sejourFiches,
		        'sjr_similaires' => $sejoursSimilaires,
		        'StringService' => $this->getStringService()
		    ));

    	}
    }

	public function retourneGalerieImagesAction () {
		$id = $this->params()->fromQuery('id');

		$galerieImages = $this->getSejourImageTable()->fetchAllArray( $id );

		echo json_encode( $galerieImages );

		return $this->response;
	}

	public function retourneCoordonneesGMapAction () {
		$id = $this->params()->fromQuery('id');

		$coordonnees_gps_sejour = $this->getSejourTable()->coordonnees_gps_sejour( $id );

		echo json_encode( $coordonnees_gps_sejour );

		return $this->response;
	}

	public function retourneAdressePageRedirectionAction () {
		$id = $this->params()->fromQuery('id');

		$pageReservation = $this->getSejourTable()->retourner_adresse_page_redirection( $id );


		$query = parse_url($pageReservation, PHP_URL_QUERY);

		$compteurAJour = $this->getSejourTable()->incrementer_compteur_page_reservation($id);

		// Returns a string if the URL has parameters or NULL if not
		if( $query ) {
		    $pageReservation .= '&source=1001treks-' . $compteurAJour;
		}
		else {
		    $pageReservation .= '?source=1001treks-' . $compteurAJour;
		}


		echo $pageReservation;

		return $this->response;
	}

	public function contactModalAction () {
		$id = $this->params()->fromQuery('id');
		$detailsSejour = $this->getSejourTable()->details_d_un_sejour_unique( $id );

		$result = new ViewModel();
	    $result->setTerminal(true);
	    $result->setVariables(array('sjr' => $detailsSejour));
	    return $result;
	}

	public function envoyerCommentaireContactAction() {

		if($_SERVER['REQUEST_METHOD'] == "POST"){
        	$values = json_decode(file_get_contents('php://input'), true);

        	/* save datas in base */
			$contactCommDatas = new Information ();
			$contactCommDatas->exchangeArray( $values );

        	if( $this->getInformationTable()->isInformationSejourDejaEnBase($contactCommDatas) ) {
				echo 'pris';
        	} else {
        		/* Sauvegarde en base du commentaire */
        		$this->traiterDemandeContact( $contactCommDatas );

        		echo json_encode( true );
			}
		}

		return $this->response;
	}

	/* Enregistre la demande de contact en base et envoi le mail */
	private function traiterDemandeContact( $contactCommDatas ) {

		$detailsSejour = $this->getSejourTable ()->details_d_un_sejour_unique( $contactCommDatas->sejourInfo );
		$sjr = $detailsSejour;

		$detailAgence = $this->getAgenceTable ()->getAgence( $sjr->agenceId );

		$this->getInformationTable()->saveInformation( $contactCommDatas );

    	$config = $this->getServiceLocator()->get('Config');
    	$root_url = $config['root_url'];

    	$dateCommentaire = $this->getDateService()->date_en_francais ( $contactCommDatas->dateInfo, '-', ':', false );

    	$sejour_url = $this->getStringService()->genererSejourUrl( 	$root_url, 
						                                        	$sjr->libelleAS, 
						                                        	$sjr->libellePays, 
						                                        	$sjr->id, 
						                                        	$sjr->titre );

    	$this->renderer = $this->getServiceLocator()->get('ViewRenderer');

    	/* Initialisation de l'image du séjour */
		$image = $this->getStringService()->RetrounerNomImageType( $sjr->imageUrl, "-main");
		$imageRechercheSejour = $root_url . "/img/galerie/sejour__" . $sjr->id . "__/". $image;

    	/* envoie des données au template du mail */
    	$content = $this->renderer->render('application/details-sejour/tpl/contact-tpl', 
    				array( 	"sjr" => $sjr,
    						"sjr_recherche_image" => $imageRechercheSejour,
	    					"contact_datas" => $contactCommDatas, 
	    					"root_url" => $root_url,
	    					"date_comment" => $dateCommentaire,
	    					"sejour_url" => $sejour_url ) );

    	/* envoi du mail */
    	$this->getMailService()->envoyer_demande_renseignement ( $sjr, $detailAgence, $contactCommDatas, $config['config_vars'], $content );
    		
    	/*envoie en copie du mail */
    	$this->getMailService()->envoyer_mail_copie ( $config['config_vars'], $content );
	}

	/*
		Action pour tester le rendu du mail
	*/
	public function mailAction () {
		$id = 1;
		$detailsSejour = $this->getSejourTable()->details_d_un_sejour_unique( $id );
		
		$sjr = $detailsSejour;

		$detailAgence = $this->getAgenceTable ()->getAgence( $sjr->agenceId );

		$contactCommDatas = $this->getInformationTable()->getSejourCommentaire ( $id );

		$dateCommentaire = $this->getDateService()->date_en_francais ( $contactCommDatas->dateCom, '-', ':', false );

		$config = $this->getServiceLocator()->get('Config');
		$root_url = $config['root_url'];

		$sejour_url = $root_url ."/" . 
							$this->getStringService()->ReecritureParametresUrl ( $sjr->libelleAS ) . "-" .
							$this->getStringService()->ReecritureParametresUrl ( $sjr->libellePays ) . "/" . $sjr->id . "-" . 
							$this->getStringService()->ReecritureParametresUrl ( $sjr->titre );


		$this->renderer = $this->getServiceLocator()->get('ViewRenderer');  
    	$content = $this->renderer->render('application/details-sejour/tpl/contact-tpl', 
    			array( 	"sjr" => $sjr, 
    					"contact_datas" => $contactCommDatas, 
    					"root_url" => $root_url,
    					"date_comment" => $dateCommentaire,
    					"sejour_url" => $sejour_url ) );

    	echo ( $content ) ;
    	// echo utf8_decode( $content ) ;

    	return $this->response;
	}


	/**************************************** MODEL OBJETS *******************************************************************/

	public function getRechercheTable()
	{
	    if (!$this->rechercheTable) {
	        $sm = $this->getServiceLocator();
	        $this->rechercheTable = $sm->get('Application\Model\RechercheTable');
	    }
	    return $this->rechercheTable;
	}

	public function getSejourTable()
	{
	    if (!$this->SejourTable) {
	        $sm = $this->getServiceLocator();
	        $this->SejourTable = $sm->get('Application\Model\SejourTable');
	    }
	    return $this->SejourTable;
	}

	public function getAgenceTable()
	{
	    if (!$this->AgenceTable) {
	        $sm = $this->getServiceLocator();
	        $this->AgenceTable = $sm->get('Application\Model\AgenceTable');
	    }
	    return $this->AgenceTable;
	}

	public function getSejourDateTable()
	{
	    if (!$this->SejourDateTable) {
	        $sm = $this->getServiceLocator();
	        $this->SejourDateTable = $sm->get('Application\Model\SejourDateTable');
	    }
	    return $this->SejourDateTable;
	}
	public function getSejourDaybydayTable()
	{
	    if (!$this->SejourDaybydayTable) {
	        $sm = $this->getServiceLocator();
	        $this->SejourDaybydayTable = $sm->get('Application\Model\SejourDaybydayTable');
	    }
	    return $this->SejourDaybydayTable;
	}
	public function getSejourFicheTable()
	{
	    if (!$this->SejourFicheTable) {
	        $sm = $this->getServiceLocator();
	        $this->SejourFicheTable = $sm->get('Application\Model\SejourFicheTable');
	    }
	    return $this->SejourFicheTable;
	}

	public function getInformationTable()
	{
	    if (!$this->InformationTable) {
	        $sm = $this->getServiceLocator();
	        $this->InformationTable = $sm->get('Application\Model\InformationTable');
	    }
	    return $this->InformationTable;
	}	

	public function getSejourImageTable()
	{
		if( !$this->SejourImageTable ){
			$sm = $this->getServiceLocator();
			$this->SejourImageTable = $sm->get("Application\Model\SejourImageTable");
		}
		return $this->SejourImageTable;
	}

	public function getActivitesSejourTable()
	{
		if( !$this->ActivitesSejourTable ){
			$sm = $this->getServiceLocator();
			$this->ActivitesSejourTable = $sm->get("Application\Model\ActivitesSejourTable");
		}
		return $this->ActivitesSejourTable;
	}

	public function getMailService()
	{
		if( !$this->MailService ){
			$sm = $this->getServiceLocator();
			$this->MailService = $sm->get("MailService");
		}

		return $this->MailService;
	}

	public function getDateService()
	{
		if( !$this->DateService ){
			$sm = $this->getServiceLocator();
			$this->DateService = $sm->get("DateService");
		}

		return $this->DateService;
	}

	public function getStringService()
	{
		if( !$this->StringService ){
			$sm = $this->getServiceLocator();
			$this->StringService = $sm->get("StringService");
		}

		return $this->StringService;
	}
}
